package zgcwkj.openqqtv;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        var mContext = getApplicationContext();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //按钮事件
        var btnOpen = (Button) findViewById(R.id.openBtn);
        btnOpen.setOnClickListener(view1 -> openApp());
        //尝试启动
        openApp();
    }

    /**
     * 监听按键事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //按钮事件
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            System.exit(0);
            return true;
        }
        //执行原有方法
        return super.onKeyDown(keyCode, event);
    }

    public void openApp() {
        var packageName = "com.ktcp.video";
        var activityName = "com.ktcp.video.activity.OpenJumpActivity";
        var isOpen = false;
        Intent intent = null;
        //方案A
        if (isOpen == false) {
            var packageManager = getPackageManager();
            intent = packageManager.getLaunchIntentForPackage(packageName);
            if (intent != null) isOpen = true;
        }
        //方案B
        if (isOpen == false) {
            intent = new Intent();
            intent.setComponent(new ComponentName(packageName, activityName));
            if (intent.resolveActivity(getPackageManager()) != null) isOpen = true;
        }
        //启动
        if (isOpen) {
            //启动应用
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
            startActivity(intent);
            //退出当前应用
            finish();
            System.exit(0);
        } else {
            //应用未安装
            Toast.makeText(this, "应用未安装", Toast.LENGTH_SHORT).show();
        }
    }
}